package com.atguigu.tingshu.search;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.search.service.ItemService;
import jakarta.annotation.Resource;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/***
 * 同步专辑数据到es中消息失败进行兜底处理
 */
@Component
public class AlbumIndexInfoMessageTsk {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    ItemService itemService;

    /**
     * 同步失败兜底函数
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void ablumIndexInfoMessageTask() {
        //从redis中获取所有失误的专辑id信息
        Set<String> albumIdSet = redisTemplate.opsForSet().members("search_up_or_down");
        //遍历处理
        albumIdSet.stream().forEach(albumId -> {
            try {
                //查询专辑数据
                AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfo(Long.valueOf(albumId));
                //判断是否公开
                CorrelationData correlationData = new CorrelationData();

                if (albumInfo.getIsOpen().equals("1")) {
                    itemService.albumInfoFromMysqlToEs(Long.valueOf(albumId));
                } else {
                    itemService.removeAlbumInfoFromMysqlToEs(Long.valueOf(albumId));
                }
                //删除这个id
                redisTemplate.opsForSet().remove("search_up_or_down", albumId);
            } catch (AmqpException e) {
                e.printStackTrace();
            }
        });
    }

}

